import json
import os

from PyQt5 import QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QMessageBox, QVBoxLayout, QDialog, QLineEdit, QPushButton, QFileDialog, QHBoxLayout

from database import TaskDatabase
from task import Task


class DownloadTask(QThread):
    progress_signal = pyqtSignal(int, int, int)  # 进度信号（已下载，文件总大小）
    speed_signal = pyqtSignal(int, float)  # 下载速度信号
    status_signal = pyqtSignal(int, str)  # 状态信号（例如“暂停”、“完成”）

    def __init__(self, url, save_path, task_id):
        super().__init__()
        self.url = url
        self.save_path = save_path
        self.task_id = task_id
        self._is_stopped = False  # 停止标志


    def run(self):
        # 模拟下载逻辑
        try:
            # 在此使用 yt_dlp 或其他下载工具进行下载
            total_size = 1000  # 假设总大小为1000KB
            downloaded = 0
            while downloaded < total_size:
                if self._is_stopped:
                    self.status_signal.emit('Paused')
                    break
                # 模拟下载过程
                downloaded += 50  # 模拟每次下载50KB
                self.progress_signal.emit(self.task_id, downloaded, total_size)
                speed = 50  # 模拟下载速度为50KB/s
                self.speed_signal.emit(self.task_id, speed)
                self.msleep(1000)  # 模拟每秒更新一次
            if downloaded >= total_size:
                self.status_signal.emit(self.task_id, 'Completed')
        except Exception as e:
            self.status_signal.emit(f'Failed: {str(e)}')

    def stop(self):
        self._is_stopped = True

    def delete(self):
        # 删除文件或清理任务的相关资源
        try:
            # 如果有文件删除或清理操作，可以在此执行
            print(f"Deleting task for URL: {self.url}")
        except Exception as e:
            print(f"Error deleting task: {str(e)}")


class DownloadManager:
    new_task = pyqtSignal(Task)
    current_tasks = []
    save_directory = ''
    db = TaskDatabase()

    def __init__(self, parent):
        self.ui = parent
        self.active_tasks = []  # 存储当前活动任务
        self.paused_tasks = []  # 存储已暂停的任务
        self.history_tasks = []  # 存储已完成的历史任务


    def add_task(self, url, save_path):
        # 添加下载任务
        task_id = self.db.insert_task(url, save_path)
        task_thread = DownloadTask(url, save_path, task_id)
        task_thread.progress_signal.connect(self.update_progress)
        task_thread.speed_signal.connect(self.update_speed)
        task_thread.status_signal.connect(self.update_status)
        self.active_tasks.append(task_thread)
        task = Task(task_id, url=url, path=save_path)
        self.new_task.emit(task)
        task_thread.start()

    def update_progress(self, downloaded, total):
        # 更新任务进度
        progress = (downloaded / total) * 100

    def update_speed(self, speed):
        # 更新下载速度
        # self.ui.speedLabel.setText(f"Speed: {speed} KB/s")  # 更新UI下载速度标签
        pass

    def update_status(self, status):
        # 更新任务状态
        # self.ui.statusLabel.setText(status)  # 更新UI状态标签
        pass

    def stop_selected_task(self):
        # 停止选中的任务
        current_row = self.ui.listWidget.currentRow()
        if current_row >= 0 and current_row < len(self.active_tasks):
            task = self.active_tasks[current_row]
            task.stop()
            self.paused_tasks.append(task)
            self.active_tasks.remove(task)
            self.ui.listWidget.takeItem(current_row)
            task.status_signal.emit('Paused')

    def stop_all_tasks(self):
        # 停止所有任务
        for task in self.active_tasks:
            task.stop()
            self.paused_tasks.append(task)
        self.active_tasks.clear()
        self.ui.listWidget.clear()
        for task in self.paused_tasks:
            task.status_signal.emit('Paused')

    def delete_selected_task(self):
        # 删除选中的任务
        current_row = self.ui.listWidget.currentRow()
        if current_row >= 0 and current_row < len(self.active_tasks):
            task = self.active_tasks[current_row]
            task.delete()  # 删除文件或清理任务
            self.active_tasks.remove(task)
            self.ui.listWidget.takeItem(current_row)
        elif current_row >= len(self.active_tasks) and current_row < len(self.paused_tasks):
            task = self.paused_tasks[current_row - len(self.active_tasks)]
            task.delete()
            self.paused_tasks.remove(task)
            self.ui.listWidget.takeItem(current_row)

    def delete_all(self):
        # 删除所有任务
        for task in self.active_tasks + self.paused_tasks:
            task.delete()  # 删除文件或清理任务
        self.active_tasks.clear()
        self.paused_tasks.clear()
        self.ui.listWidget.clear()

    def resume_selected_task(self):
        # 恢复选中的任务
        current_row = self.ui.listWidget.currentRow()
        if current_row >= len(self.active_tasks) and current_row < len(self.paused_tasks) + len(self.active_tasks):
            task = self.paused_tasks[current_row - len(self.active_tasks)]
            task.start()
            self.active_tasks.append(task)
            self.paused_tasks.remove(task)
            self.ui.listWidget.takeItem(current_row)
            task.status_signal.emit('Resumed')

    def remove_paused_task(self):
        # 移除暂停中的任务
        current_row = self.ui.listWidget.currentRow()
        if current_row >= len(self.active_tasks) and current_row < len(self.paused_tasks) + len(self.active_tasks):
            task = self.paused_tasks[current_row - len(self.active_tasks)]
            self.paused_tasks.remove(task)
            self.ui.listWidget.takeItem(current_row)

    def remove_all_paused(self):
        # 移除所有暂停中的任务
        for task in self.paused_tasks:
            self.ui.listWidget.takeItem(self.ui.listWidget.row(task))
        self.paused_tasks.clear()

    def resume_all(self):
        # 恢复所有任务
        for task in self.paused_tasks:
            task.start()
            self.active_tasks.append(task)
        self.paused_tasks.clear()
        self.ui.listWidget.clear()
        task.status_signal.emit('Resumed')

    def redownload_failed_task(self):
        # 重新下载失败的任务
        pass  # 需要实现

    def redownload_all_failed(self):
        # 重新下载所有失败的任务
        pass  # 需要实现

    def remove_failed_task(self):
        # 删除失败的任务
        pass  # 需要实现

    def clear_all_history(self):
        # 清空所有历史记录
        self.history_tasks.clear()
        self.ui.historyListWidget.clear()

    def add_task_dialog(self, parent):
        # 创建对话框
        dialog = QDialog(parent)
        dialog.setWindowTitle("添加下载任务")
        dialog.resize(600, 150)

        # 创建输入框和按钮
        url_label = QLineEdit(dialog)
        url_label.setPlaceholderText("请输入视频链接")
        save_path_label = QLineEdit(dialog)
        save_path_label.setPlaceholderText("请输入保存路径, 留空为默认保存目录")
        browse_button = QPushButton("浏览", dialog)

        def browse():
            # 打开文件对话框，选择保存目录
            folder = QFileDialog.getExistingDirectory(dialog, "选择保存目录")
            save_path_label.setText(folder)

        browse_button.clicked.connect(browse)

        add_button = QPushButton("添加任务", dialog)

        def add_task():
            url = url_label.text()
            save_path = save_path_label.text()
            if save_path is None or save_path == '':
                save_path = self.save_directory
            if url:
                self.add_task(url, save_path)  # 调用添加任务的方法
                dialog.accept()  # 关闭对话框
            else:
                # 提示输入错误
                QMessageBox.warning(dialog, "输入错误", "请确保填写完整的链接和保存路径")

        add_button.clicked.connect(add_task)

        # 设置对话框布局
        layout = QVBoxLayout(dialog)
        layout.addWidget(url_label)
        layout.addWidget(save_path_label)
        vertical_spacer = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum,
                                                QtWidgets.QSizePolicy.Expanding)  # 创建垂直间隔
        layout.addItem(vertical_spacer)  # 将垂直间隔添加到布局中
        horizontal_layout = QHBoxLayout()
        horizontal_layout.addWidget(browse_button)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        horizontal_layout.addItem(spacerItem)
        horizontal_layout.addWidget(add_button)
        layout.addLayout(horizontal_layout)
        dialog.setLayout(layout)
        dialog.exec_()  # 显示对话框

    def open_settings(self, parent):
        # 创建设置对话框
        settings_dialog = QDialog(parent)
        settings_dialog.setWindowTitle("设置")
        settings_dialog.resize(600,120)

        # 创建保存路径输入框
        save_path_label = QLineEdit(settings_dialog)
        save_path_label.setPlaceholderText("请输入默认保存路径")
        save_path_label.setText(self.get_current_save_path())  # 假设这是获取当前保存路径的方法


        # 创建浏览按钮
        browse_button = QPushButton("浏览", settings_dialog)

        def browse():
            # 打开文件对话框选择目录
            folder = QFileDialog.getExistingDirectory(settings_dialog, "选择保存目录")
            save_path_label.setText(folder)

        browse_button.clicked.connect(browse)

        # 创建保存按钮
        save_button = QPushButton("保存", settings_dialog)

        def save():
            new_save_path = save_path_label.text()
            if new_save_path:
                self.update_save_path(new_save_path)  # 假设这个方法更新保存路径
                settings_dialog.accept()  # 关闭对话框
            else:
                QMessageBox.warning(settings_dialog, "输入错误", "请确保填写保存路径")

        save_button.clicked.connect(save)

        # 设置对话框布局
        layout = QVBoxLayout(settings_dialog)
        layout.addWidget(save_path_label)
        horizontal_layout = QHBoxLayout()
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        horizontal_layout.addWidget(browse_button)
        horizontal_layout.addItem(spacerItem)
        horizontal_layout.addWidget(save_button)
        layout.addLayout(horizontal_layout)

        settings_dialog.setLayout(layout)
        settings_dialog.exec_()  # 显示设置对话框

    def get_current_save_path(self):
        try:
            with open('config.json', 'r', encoding='utf-8') as f:
                configs = json.load(f)
                return configs['default_save_directory']
        except:
            default_dir = './downloads'
            if not os.path.exists(default_dir):
                os.mkdir(default_dir)
            return os.path.abspath(default_dir)

    def update_save_path(self, new_path):
        # 在这里更新保存路径
        self.save_directory = new_path
        with open('config.json', 'w', encoding='utf-8') as f:
            json.dump({'default_save_directory': new_path},f, ensure_ascii=False)

    def remove_selected_history(self):
        # 获取选中的历史任务（假设通过 UI 控件获取）
        selected_task = self.get_selected_history_task()

        if selected_task:
            self.history_tasks.remove(selected_task)  # 从历史任务列表中移除
            print(f"已删除历史任务: {selected_task}")
            # 更新 UI 显示
            self.update_history_list_ui()
        else:
            print("没有选择历史任务")

    def get_selected_history_task(self):
        # 假设你有一个方法用来从 UI 获取选中的历史任务
        # 你需要根据 UI 组件获取实际的选中任务。这里是示例代码
        selected_task = None  # 在这里你可以根据实际情况从 UI 获取选中的任务
        return selected_task

    def update_history_list_ui(self):
        # 更新 UI 中历史任务列表的显示
        pass  # 实现这个方法以更新 UI，例如通过 QTableWidget 或其他控件

    def remove_all_failed(self):
        # 清空所有失败任务
        if self.failed_tasks:
            self.failed_tasks.clear()  # 删除所有失败任务
            print("已删除所有失败任务")
            # 更新 UI 显示
            self.update_failed_tasks_ui()
        else:
            print("没有失败任务")

    def update_failed_tasks_ui(self):
        # 更新 UI 中失败任务列表的显示
        pass  # 根据 UI 更新失败任务的显示，例如更新表格、列表等
